#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
自定义异常类
定义交易框架中使用的各种异常
"""


class TqSdkTraderError(Exception):
    """TqSdk Trader基础异常类"""
    pass


class ConfigError(TqSdkTraderError):
    """配置相关异常"""
    pass


class APIError(TqSdkTraderError):
    """API相关异常"""
    pass


class AuthenticationError(APIError):
    """认证失败异常"""
    pass


class ConnectionError(APIError):
    """连接异常"""
    pass


class TimeoutError(APIError):
    """超时异常"""
    pass


class DataError(TqSdkTraderError):
    """数据相关异常"""
    pass


class SymbolNotFoundError(DataError):
    """合约未找到异常"""
    pass


class DataUnavailableError(DataError):
    """数据不可用异常"""
    pass


class TradingError(TqSdkTraderError):
    """交易相关异常"""
    pass


class OrderError(TradingError):
    """订单相关异常"""
    pass


class OrderRejectedError(OrderError):
    """订单被拒绝异常"""
    def __init__(self, message: str, order_id: str = None, reason: str = None):
        super().__init__(message)
        self.order_id = order_id
        self.reason = reason


class OrderTimeoutError(OrderError):
    """订单超时异常"""
    def __init__(self, message: str, order_id: str = None, timeout: int = None):
        super().__init__(message)
        self.order_id = order_id
        self.timeout = timeout


class InsufficientFundsError(TradingError):
    """资金不足异常"""
    pass


class PositionError(TradingError):
    """持仓相关异常"""
    pass


class RiskError(TqSdkTraderError):
    """风险控制相关异常"""
    pass


class StopLossTriggeredError(RiskError):
    """止损触发异常"""
    def __init__(self, message: str, symbol: str, entry_price: float, current_price: float):
        super().__init__(message)
        self.symbol = symbol
        self.entry_price = entry_price
        self.current_price = current_price


class DailyLossLimitError(RiskError):
    """日亏损限制异常"""
    def __init__(self, message: str, current_loss: float, max_loss: float):
        super().__init__(message)
        self.current_loss = current_loss
        self.max_loss = max_loss


class StrategyError(TqSdkTraderError):
    """策略相关异常"""
    pass


class StrategyInitializationError(StrategyError):
    """策略初始化异常"""
    pass


class StrategyExecutionError(StrategyError):
    """策略执行异常"""
    pass


class ValidationError(TqSdkTraderError):
    """验证相关异常"""
    pass


class ParameterError(ValidationError):
    """参数错误异常"""
    pass


class StateError(TqSdkTraderError):
    """状态相关异常"""
    pass


class SystemError(TqSdkTraderError):
    """系统级异常"""
    pass


class MonitoringError(SystemError):
    """监控相关异常"""
    pass


class PerformanceError(SystemError):
    """性能相关异常"""
    pass


# 异常处理装饰器
def handle_exceptions(logger=None, re_raise: bool = True):
    """
    异常处理装饰器

    Args:
        logger: 日志器实例
        re_raise: 是否重新抛出异常
    """
    def decorator(func):
        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except TqSdkTraderError:
                # 框架内部异常，直接抛出
                if logger:
                    logger.exception(f"TqSdk Trader 异常: {func.__name__}")
                if re_raise:
                    raise
            except Exception as e:
                # 其他异常，包装成系统异常
                error_msg = f"系统异常 in {func.__name__}: {str(e)}"
                if logger:
                    logger.exception(error_msg)
                if re_raise:
                    raise SystemError(error_msg) from e
        return wrapper
    return decorator


def retry_on_exception(max_attempts: int = 3, delay: float = 1.0, exceptions: tuple = (APIError, ConnectionError)):
    """
    重试装饰器

    Args:
        max_attempts: 最大重试次数
        delay: 重试间隔(秒)
        exceptions: 需要重试的异常类型
    """
    def decorator(func):
        def wrapper(*args, **kwargs):
            last_exception = None

            for attempt in range(max_attempts):
                try:
                    return func(*args, **kwargs)
                except exceptions as e:
                    last_exception = e
                    if attempt < max_attempts - 1:
                        import time
                        time.sleep(delay * (2 ** attempt))  # 指数退避
                    else:
                        break

            # 所有重试都失败，抛出最后一次异常
            raise last_exception
        return wrapper
    return decorator


def validate_parameters(**validators):
    """
    参数验证装饰器

    Args:
        validators: 参数验证函数字典
    """
    def decorator(func):
        def wrapper(*args, **kwargs):
            # 获取函数参数名
            import inspect
            sig = inspect.signature(func)
            bound_args = sig.bind(*args, **kwargs)
            bound_args.apply_defaults()

            # 验证参数
            for param_name, validator in validators.items():
                if param_name in bound_args.arguments:
                    value = bound_args.arguments[param_name]
                    if not validator(value):
                        raise ParameterError(f"参数 {param_name} 验证失败: {value}")

            return func(*args, **kwargs)
        return wrapper
    return decorator


# 验证函数
def validate_positive_number(value):
    """验证正数"""
    return isinstance(value, (int, float)) and value > 0


def validate_non_negative_number(value):
    """验证非负数"""
    return isinstance(value, (int, float)) and value >= 0


def validate_symbol(symbol):
    """验证合约代码"""
    if not isinstance(symbol, str):
        return False
    return len(symbol.split('.')) == 2


def validate_order_direction(direction):
    """验证订单方向"""
    return direction in ['BUY', 'SELL']


def validate_order_offset(offset):
    """验证开平标志"""
    return offset in ['OPEN', 'CLOSE', 'CLOSETODAY']
